<template>
<div id="login">
  <div class="login-wrap">
    <ul class="menu-tab">
      <li :class="{'current': item.current } " v-for="(item) in textTab" :key="item.id" @click="toggleMenu(item)">{{item.text}}</li>
    </ul>
    <!-- 表单 -->
    <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" class="login-form">
      <el-form-item prop="userMail" class="item-form">
        <label for="userMail">邮箱</label>
        <el-input id="userMail" type="text" v-model="loginForm.userMail" autocomplete="off" size="medium "></el-input>
      </el-form-item>
      <el-form-item prop="password" class="item-form">
        <label for="password">密码</label>
        <el-input id="password" type="text" v-model="loginForm.password" autocomplete="off" size="medium" minlength="6" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item prop="code" class="item-form">
        <label for="code">验证码</label>
        <el-row :gutter="10">
          <el-col :span="15">
            <el-input id="code" v-model="loginForm.code" minlength="6" maxlength="6" size="medium"></el-input>
          </el-col>
          <el-col :span="9">
            <el-button class="block" type="success" size="medium" @click="getSms()" :disabled="codeButtonStatus.status">
              {{codeButtonStatus.text}}
              <i class="el-icon-loading" v-if="codeButtonStatus.text == '发送中'"></i>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="submitForm('loginForm')" :disabled=" loginButtonStatus " class="login-btn block">{{model=='register' ? "注册" : "登陆" }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script>
import {
  reactive,
  ref,
  isRef,
  toRefs,
  onMounted
} from "@vue/composition-api";
import {stripscript,validateEmail,validatePass,validateCode} from "@/utils/validate";
import sha1 from "js-sha1";
import {  GetSms,  Register,  Login} from "@/api/login";
import {
  constants
} from "fs";

export default {
  name: "login",
  setup(props, {
    refs,
    root
  }) {
    // 验证用户名为 邮箱
    let validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (!validateEmail(value)) {
        callback(new Error("用户名格式有误"));
      } else {
        callback();
      }
    };
    // 验证密码
    let validatePassword = (rule, value, callback) => {
      loginForm.password = stripscript(value);
      value = loginForm.password;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!validatePass(value)) {
        callback(new Error("密码为6-20位数字+字母"));
      } else {
        callback();
      }
    };
    // 验证码 验证
    let checkCode = (rule, value, callback) => {
      loginForm.code = stripscript(value);
      value = loginForm.code;
      if (!value) {
        return callback(new Error("请输入验证码"));
      } else if (!validateCode(value)) {
        return callback(new Error("验证码格式有误"));
      } else {
        callback();
      }
    };
    // 获取验证码
    const getSms = () => {
      if (loginForm.userMail == "") {
        root.$message({
          showClose: true,
          message: "邮箱不能为空",
          type: "error"
        });
        return;
      }
      if (!validateEmail(loginForm.userMail)) {
        root.$message({
          showClose: true,
          message: "邮箱格式有误，请重新输入！！",
          type: "error"
        });
        return;
      }
      // 修改获取验证码按钮状态
      updataCodeButtonStatus({
        text: "发送中",
        status: true
      });

      // 延迟提交
      GetSms({
          userMail: loginForm.userMail
        })
        .then(response => {
          let data = response.data;
          console.log("========", data);
          root.$message({
            showClose: true,
            message: data.message,
            type: "success"
          });
          loginButtonStatus.value = false;
          console.log(response.data);
          // 调用定时器 请求倒计时
          countDown(60);
        })
        .catch(err => {
          updataCodeButtonStatus({
            text: "重新获取",
            status: false
          });
        });
    };
    // 提交表单
    const submitForm = formName => {
      // getSms();
      refs[formName].validate(valid => {
        if (valid) {
          let requestData = {
            userMail: loginForm.userMail,
            password: sha1(loginForm.password),
            code: loginForm.code
          };
          root.$store
            .dispatch("login", requestData)
            .then(res => {
              console.log(res.data);

              console.log("=====", res);
              // 登陆成功 路由跳转
              root.$router.push({
                name: "Console"
              });
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    // 这里放置data数据 生命周期 自定义函数
    const textTab = reactive([{
      text: "登陆",
      current: true,
      type: "login"
    }]);
    const model = ref("login");
    const loginButtonStatus = ref(true);
    const codeButtonStatus = reactive({
      status: false,
      text: "获取验证码"
    });
    // 表单数据
    const loginForm = reactive({
      userMail: "qx_qing@yeah.net",
      password: "123456a",
      code: ""
    });
    // 表单验证
    const rules = reactive({
      userMail: [{
        validator: validateUsername,
        trigger: "blur"
      }],
      password: [{
        validator: validatePassword,
        trigger: "blur"
      }],
      code: [{
        validator: checkCode,
        trigger: "blur"
      }]
    });

    // 声明函数
    const toggleMenu = item => {
      textTab.forEach(e => {
        e.current = false;
      });
      item.current = true;
      model.value = item.type;
      // 重置表单
      resetFromData();
      // 清除定时器
      clearTimer();
    };
    const updataCodeButtonStatus = params => {
      codeButtonStatus.text = params.text;
      codeButtonStatus.status = params.status;
    };

    const resetFromData = () => {
      refs.loginForm.resetFields();
      updataCodeButtonStatus({
        text: "获取验证码",
        status: false
      });
      loginButtonStatus.value = true;
    };

    const timer = ref(null);
    // 倒计时
    const clearTimer = () => {
      clearInterval(timer.value);
    };
    const countDown = number => {
      clearTimer();
      let count = number;
      codeButtonStatus.text = `倒计时${count}秒`;
      timer.value = setInterval(() => {
        if (count <= 0) {
          updataCodeButtonStatus({
            text: "重新获取",
            status: false
          });
          clearTimer();
        } else {
          count--;
          codeButtonStatus.text = `倒计时${count}秒`;
        }
      }, 1000);
    };
    // 生命周期
    onMounted(() => {
      console.log("挂载完成后");
    });
    return { textTab,  model,  loginButtonStatus,    codeButtonStatus,
      loginForm,    toggleMenu,   rules,     submitForm,      getSms
    };
  }
};
</script>

<style lang="scss" scoped>
#login {
  height: 100vh;
  background-color: #344a5f;
}

.login-wrap {
  width: 330px;
  margin: auto;
}

.menu-tab {
  text-align: center;

  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    border-radius: 2px;
    color: white;
    cursor: pointer;
  }

  .current {
    background-color: rgba(0, 0, 0, 0.1);
  }
}

.login-form {
  margin-top: 29px;

  label {
    display: block;
    font-size: 14px;
    color: #fff;
    margin-bottom: 3px;
  }

  .item-form {
    margin-bottom: 13px;
  }

  .block {
    width: 100%;
    display: block;
  }

  .login-btn {
    margin-top: 19px;
  }
}
</style>
